﻿using EyFramework.Sys.Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EyFramework.ORM;
using EyFramework.Task.Entity;
using Newtonsoft.Json;

namespace EyFramework.Task.Excutor
{
    public class SqlJobExecutor : IJobExecutor
    {
        public ReturnData Execute(QrtzCsTask pTaskInfo)
        {
            ReturnData rd = new ReturnData();
            SqlInfo ui = JsonConvert.DeserializeObject<SqlInfo>(pTaskInfo.TASK_INFO);
            try
            {
                DataTable dt = DbHelper.SelectTable(ui.SQL);
                if (dt.Rows.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    List<string> columns = GetColumnsByDataTable(dt);
                    //最多显示10条结果
                    int index = 1;
                    foreach (DataRow row in dt.Rows)
                    {
                        if (index > 10)
                        {
                            break;
                        }
                        sb.Append(index++).Append("、");
                        foreach (string column in columns)
                        {
                            sb.Append(column).Append(":").Append(row[column].ToString() + "\r\n");
                        }
                    }
                    rd.Fail(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                rd.Fail("SQL任务执行失败:" + ex.ToString());
            }
            return rd;
        }

        private List<string> GetColumnsByDataTable(DataTable dt)
        {
            List<string> columns = new List<string>();

            if (dt.Columns.Count > 0)
            {
                int columnNum = 0;
                columnNum = dt.Columns.Count;
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    columns.Add(dt.Columns[i].ColumnName);
                }
            }
            return columns;
        }
    }
}